import axios from 'axios'
import qs from 'qs'
import util from '../utils/utils'
import utils from "@/utils/utils"
// let baseURL = 'http://huankeyanxue.com/api'
let baseURL = '/api'
if (process.env.NODE_ENV === 'production') {
    if (window.location.host === 'cs.huankeyanxue.com') {
        baseURL = 'http://csplat.huankeyanxue.com/api'
    } else {
        baseURL = 'https://platform.huankeyanxue.com/api'
    }
}

axios.defaults.baseURL = baseURL

// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
// 请求拦截器
axios.interceptors.request.use(config => {
    const {method} = config
    const baseId = util.getUrlParam('base')
    if (baseId) {
        config.headers['base'] = baseId
        if (method === 'post') {
            if (!config.data) {
                config.data = {}
            }
            config.data.base = baseId
        }
        if (method === 'get') {
            if (!config.params) {
                config.params = {}
            }
            config.params.base = baseId
        }
    }

    if (config.method === 'post' &&
        !config.url.includes('/v1.0/user/updateAvatar') &&
        !config.url.includes('/v1.0/common/upload')) {
        if (config.data) {
            config.data = qs.stringify(config.data)
        }
    }
    let token = window.localStorage.getItem('token')
    if (window.__wxjs_environment === 'miniprogram') {
        token = window.localStorage.getItem('miniAppToken')
    }
    if (token) {
        config.headers['token'] = token
    } else {
        config.headers['token'] = ''
    }
    return config
}, function (error) {
    return Promise.reject(error)
})

// 响应拦截器
axios.interceptors.response.use(response => {
    const {data, config} = response
    if (config.url.includes('/captcha/captchaImagePC')) {
        return Promise.resolve(data)
    }
    if (data.code && data.code === 200) {
        return Promise.resolve(data)
    } else {
        return Promise.reject(data)
    }
}, error => {
    return Promise.reject(error)
})


export default axios
